import TSpace.*;
import org.omg.CosNaming.*;
import org.omg.CosNaming.NamingContextPackage.*;
import org.omg.CORBA.*;
import org.omg.PortableServer.*;

import java.util.LinkedList;
import java.util.List;
import java.util.Properties;
import java.util.Random;

public class TSServer
{
	private ORB                  orb;
	private TupleImplementation  tupleImplementation;

	public TSServer(String args[], int spaceNumber)
	{
		try
		{
			// create and initialize the ORB
			orb = ORB.init(args, null);

			// get reference to rootpoa & activate the POAManager
			POA rootpoa = POAHelper.narrow(orb.resolve_initial_references("RootPOA"));
			rootpoa.the_POAManager().activate();

			// create servant and register it with the ORB
			tupleImplementation = new TupleImplementation();
			tupleImplementation.setORB(orb); 

			// get object reference from the servant
			org.omg.CORBA.Object ref = rootpoa.servant_to_reference(tupleImplementation);
			TupleSpace href = TupleSpaceHelper.narrow(ref);

			// get the root naming context
			org.omg.CORBA.Object objRef = orb.resolve_initial_references("NameService");

			// Use NamingContextExt which is part of the Interoperable
			// Naming Service (INS) specification.
			NamingContextExt ncRef = NamingContextExtHelper.narrow(objRef);

			// bind the Object Reference in Naming
			String name = "TupleSpace" + spaceNumber;
			NameComponent path[] = ncRef.to_name( name );
			ncRef.rebind(path, href);
		} 	
		catch (Exception e)
		{
			System.err.println("ERROR: " + e);
			e.printStackTrace(System.out);
		}
	  
		System.out.println("TupleSpaceServer Initialized ...");	
	}

	public void run()
	{	
		System.out.println("TupleSpaceServer ready and waiting ...");

		try
		{
			// wait for invocations from clients
			orb.run();
		} 	
		catch (Exception e)
		{
			System.err.println("ERROR: " + e);
			e.printStackTrace(System.out);
		}
	  
		System.out.println("TupleSpaceServer Exiting ...");	
	}

	public void update(Tuple[] tuples)
	{
//		int random_counter2 = (new Random()).nextInt() << 16;

		for (Tuple tup : tuples)
		{
//			++random_counter2;
//			TupleRequest req = new TupleRequest(random_counter2, tup);
			tupleImplementation.addTuple(tup);
		}
	}

	public TupleImplementation getTupleImplementation()
	{
		return tupleImplementation;
	}
}

